<?php
require_once 'Loans.php';
require_once 'Payments.php';
require_once 'LoanStatusChanges.php';
require_once 'LoanWriteOffCharges.php';
require_once 'LoanWriteOffPayments.php';
require_once '../application/modules/savings/models/SavingsAccounts.php';

class Loan_PaymentController extends HTech_Controller_Action
{
    function init()
    {
        $cfg = array(
            'model' => 'Payments',
            'flashMessenger' => true,
            'actionContext' => array(
                'plan' => array('prn','mob'), 
                'status-changes' => array('prn','mob'),
                'write-off-charges' => array('prn','mob'),
                'write-off-payments' => array('prn','mob'),
                'view' => array('prn','mob'))
        );
        parent::init($cfg); 
    }
    
    public function principalAction() 
    {
        try {
            $this->view->pmt = new Emms_EarlyPayment((int) $this->_request->getParam('id'));
        } catch (Exception $e) {
            $this->_helper->flashMessenger->addMessage($e->getMessage());
            $this->redirect('/default/auth/deny'); 
        }
        
        $this->view->form = new Emms_Form_Loan_PaymentPrincipal($this->view->pmt);
        
        if ($this->getRequest()->isPost()) {
            if ($this->view->form->isValid($this->getRequest()->getPost())) {
                try {
                    $paymentId = $this->view->pmt->pay($this->view->form->getValue('Amount'));
                } catch (Exception $e) {
                    echo $e->getMessage();
                }  
                $this->redirect(sprintf('/loan/loan/plan/id/%s',$this->view->pmt->getLoanId())); 
            }
        }
        $this->_helper->layout->setLayout('form');
    }
    
    public function fullAction() {
        parent::viewAction();
        $this->view->Plan = new Emms_PmtPlan(new Emms_Loan($this->view->Loans->d->LoanId));
        $savings = new SavingsAccounts();
        $this->view->Savings = $savings->find($this->view->Loans->d->ClientId)->current();
    }
}
